using UnityEngine;
using System.Collections;

public class WowadiusUpdateHP : MonoBehaviour
{
    #region Input params
    public int MaxHP = 3;
    public GameObject ExplosionPref = null;
    public AudioClip ExplosionSFX = null;
    #endregion

    #region Private fields
    private const float SECOND_TILL_DESTROY = 1.5f;

    private int _currentHP = 3;
    private float _deathTimer = 0f;
    private bool _lastBreath = false;
    #endregion

    void Awake()
    {
        //Init max HP
        _currentHP = MaxHP;
    }

    void FixedUpdate()
    {
        if (_currentHP == 0)
        {
            //Start death count sequence
            _deathTimer += Time.deltaTime;
            //Move aimlessly ;)
            if (!_lastBreath)
            {
                rigidbody.isKinematic = false;
                rigidbody.drag = 0f;
                rigidbody.AddForce(new Vector3(Random.Range(-200, 200), Random.Range(-50, 50), 0));
                rigidbody.rotation = new Quaternion(Random.value, Random.value, Random.value, Random.value);
                //Tell the owner that it's being destroyed
                gameObject.SendMessage(WowadiusConstant.CustomMessage.BEING_DESTROY);
                _lastBreath = true;
            }
        }

        //Ok, enough kill me now!
        if (_deathTimer >= SECOND_TILL_DESTROY)
            DestroyMe();
    }

    /// <summary>
    /// Process taking damage
    /// </summary>
    /// <param name="damageInflict">
    /// A <see cref="System.Int32"/>
    /// </param>
    void OnTakingDamage(int damageInflict)
    {
        //Reduce HP
        if (_currentHP > 0)
            _currentHP -= damageInflict;
    }

    /// <summary>
    /// Destroy the game object
    /// </summary>
    private void DestroyMe()
    {
        //Explosion
        Instantiate(ExplosionPref, transform.position, Quaternion.identity);
        AudioSource.PlayClipAtPoint(ExplosionSFX, transform.position);
        //Then destroy
        Destroy(gameObject);
    }
}
